package org.example;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Package.json依赖分析器
 * 用于解析package.json文件中的依赖并生成Excel表格
 */
public class PackageJsonAnalyzer {
    
    private final ObjectMapper objectMapper;
    
    public PackageJsonAnalyzer() {
        this.objectMapper = new ObjectMapper();
    }
    
    /**
     * 解析package.json文件中的依赖
     * @param packageJsonPath package.json文件的路径
     * @return 依赖列表
     * @throws IOException 如果文件读取失败
     */
    public List<Dependency> parseDependencies(String packageJsonPath) throws IOException {
        File file = new File(packageJsonPath);
        if (!file.exists()) {
            throw new IOException("文件不存在: " + packageJsonPath);
        }
        
        JsonNode rootNode = objectMapper.readTree(file);
        List<Dependency> dependencies = new ArrayList<>();
        
        // 解析dependencies
        if (rootNode.has("dependencies")) {
            JsonNode depsNode = rootNode.get("dependencies");
            parseDependencyNode(depsNode, dependencies, "dependencies");
        }
        
        // 解析devDependencies
        if (rootNode.has("devDependencies")) {
            JsonNode devDepsNode = rootNode.get("devDependencies");
            parseDependencyNode(devDepsNode, dependencies, "devDependencies");
        }
        
        // 解析peerDependencies
        if (rootNode.has("peerDependencies")) {
            JsonNode peerDepsNode = rootNode.get("peerDependencies");
            parseDependencyNode(peerDepsNode, dependencies, "peerDependencies");
        }
        
        return dependencies;
    }
    
    /**
     * 解析依赖节点
     * @param depsNode 依赖节点
     * @param dependencies 依赖列表
     * @param type 依赖类型
     */
    private void parseDependencyNode(JsonNode depsNode, List<Dependency> dependencies, String type) {
        if (depsNode.isObject()) {
            depsNode.fields().forEachRemaining(entry -> {
                String name = entry.getKey();
                String version = entry.getValue().asText();
                dependencies.add(new Dependency(name, version, type));
            });
        }
    }
    
    /**
     * 将依赖列表写入Excel文件
     * @param dependencies 依赖列表
     * @param outputPath 输出Excel文件路径
     * @throws IOException 如果文件写入失败
     */
    public void writeToExcel(List<Dependency> dependencies, String outputPath) throws IOException {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("依赖列表");
            
            // 创建标题行样式
            CellStyle headerStyle = createHeaderStyle(workbook);
            
            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] headers = {"库名", "版本号", "依赖类型"};
            
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
            }
            
            // 写入数据
            for (int i = 0; i < dependencies.size(); i++) {
                Dependency dep = dependencies.get(i);
                Row row = sheet.createRow(i + 1);
                
                row.createCell(0).setCellValue(dep.getName());
                row.createCell(1).setCellValue(dep.getVersion());
                row.createCell(2).setCellValue(dep.getType());
            }
            
            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }
            
            // 写入文件
            try (FileOutputStream fileOut = new FileOutputStream(outputPath)) {
                workbook.write(fileOut);
            }
        }
    }
    
    /**
     * 创建标题行样式
     * @param workbook 工作簿
     * @return 单元格样式
     */
    private CellStyle createHeaderStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);
        style.setFont(font);
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        return style;
    }
    
    /**
     * 依赖信息类
     */
    public static class Dependency {
        private final String name;
        private final String version;
        private final String type;
        
        public Dependency(String name, String version, String type) {
            this.name = name;
            this.version = version;
            this.type = type;
        }
        
        public String getName() {
            return name;
        }
        
        public String getVersion() {
            return version;
        }
        
        public String getType() {
            return type;
        }
        
        @Override
        public String toString() {
            return "Dependency{" +
                    "name='" + name + '\'' +
                    ", version='" + version + '\'' +
                    ", type='" + type + '\'' +
                    '}';
        }
    }
}
